<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="电影搜索" @click-left="$router.push('/films/nowplaying')">
      <template #left>
        <span>首页</span>
      </template>
    </van-nav-bar>
    <!-- 搜索 -->
    <form action="/">
      <van-search
        v-model="q"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @input="suggestInputFn"
        @cancel="$router.replace('/films/nowplaying')"
      />
    </form>
    <!-- 搜索的结果 -->
    <search v-if="searchData.length > 0" :searchData="searchData" />

    <!-- 联想建议搜索 -->
    <suggest v-if="q != '' && searchData.length == 0" :suggestData="suggestData" />

    <!-- 搜索的历史 -->
    <history v-if="q == '' && searchData.length == 0" :histories="histories" @delsearchitem="delsearchitem" />
  </div>
</template>

<script>
// lodash实现防抖
import _ from 'lodash'
import { searchApi } from '@/api/searchApi'
import sessionStore from '@/utils/Store'
import History from './ui/history.vue'
import Suggest from './ui/suggest.vue'
import Search from './ui/search.vue'
export default {
  components: {
    History,
    Suggest,
    Search,
  },
  data() {
    return {
      // 搜索关键词   联想搜索关键词
      q: '',
      histories: sessionStore.get('history') == '' ? [] : sessionStore.get('history'),
      suggestData: [],
      searchData: [],
    }
  },
  methods: {
    // 用户输入数据后，进行联想建议查询  使用防抖来实际联想搜索优化 throttle节流
    suggestInputFn: _.debounce(async function (value) {
      if (value === '') this.searchData = []
      try {
        let ret = await searchApi(value)
        // console.log(ret)
        this.suggestData = ret.movies.list
      } catch (error) {}
    }, 200),
    delsearchitem(index) {
      this.histories = sessionStore.get('history') == '' ? [] : sessionStore.get('history')
      this.histories.splice(index, 1)
      sessionStore.set('history', this.histories)
    },
    async onSearch(val) {
      // 用户在手机端点击搜索或在pc上回车触发，触发后将数据存储到本地
      // 在本地获取数据，如果没有则直接添加
      let histories = sessionStore.get('history') == '' ? [] : sessionStore.get('history')
      if (!histories.includes(val)) {
        // 关键词还不存在
        // 不关心队列中有多少
        histories.unshift(val)
        histories = histories.slice(0, 10)
      }
      // 写入到存储中
      sessionStore.set('history', histories)
      this.histories = histories

      // 进行网络请求 -- 回车搜索
      try {
        let ret = await searchApi(val)
        this.searchData = ret.movies.list
      } catch (error) {}
    },
  },
}
</script>

<style lang="scss" scoped>
</style>